package com.ch.d0312.d0316;

import com.ch.bean.Result;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.UUID;

@WebServlet(name = "UploadImageServlet", value = "/UploadImageServlet.s")
public class UploadImageServlet extends HttpServlet {

    public static final String IMAGE_PATH = "";
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        Result result;
        try {
            final Part image = request.getPart("image");
            // 提取文件会缀名
            final String suffix = image.getSubmittedFileName().replaceAll(".+(\\.\\w+)","$1");
            // 生成随机文件名
            String filenmae = UUID.randomUUID().toString();
            filenmae = filenmae.replaceAll("-","");
            filenmae += suffix;
            //保存文件
            image.write(IMAGE_PATH + filenmae);
            // 构建 上传文件 的 web路径
            String webpath = "/upload/" + filenmae;
            result = new Result(1,"文件上传成功",webpath);
        }catch (Exception e){
            e.printStackTrace();
            result = new Result(0,"文件夹上传失败",null);
        }
        final String json = new Gson().toJson(result);
        response.getWriter().append(json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
